package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import artid.com.arttogoa.R;

import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.parser.ClasslistParse;
import artid.com.arttogoa.parser.DefaultAddressParser;
import artid.com.arttogoa.parser.OneStateParser;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：MyDeliverGoods_Activity   
 * 类描述   ：我要发货   
 * 创建人   ：耿卫斌   
 * 创建时间：2016-7-27 下午5:00:30   
 *
 */
public class MyDeliverGoods_Activity extends BaseActivity implements OnClickListener{
	private Context mContext;
	private LinearLayout sunFengLL,emsLL;
	private RelativeLayout addressRL;
	private ImageView sunFengCheck,emsCheck;
	private TextView titleRight_tv,goods_address;
	private EditText expressNumberEd;
	private String express,express_id;//快递公司(默认顺丰) 和快递公司ID（默认ID：29）
	private String order_id;//订单ID
	private String address_id;//地址ID
	private List<ClasslistParse.Classlist> list_express;//快递信息
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mydelivergoods);
		mContext=MyDeliverGoods_Activity.this;
		setContent(this, getIntent());
		initView();
	}
	private void initView(){
		mTittle.setText("我要发货");
		setBack();
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.MyDeliverGoods_Activity.receiver");
		registerReceiver(broadcastReceiver, filter);
		order_id=getIntent().getStringExtra("order_id");
		titleRight_tv=(TextView) findViewById(R.id.title_right);
		titleRight_tv.setText("确认");
		titleRight_tv.setVisibility(View.VISIBLE);
		titleRight_tv.setOnClickListener(this);
		titleRight_tv.setEnabled(false);
		titleRight_tv.setTextColor(Color.parseColor("#D0D0D0"));
		sunFengLL=(LinearLayout) findViewById(R.id.mydelivergoods_sunfeng);
		sunFengLL.setOnClickListener(this);
		emsLL=(LinearLayout) findViewById(R.id.mydelivergoods_ems);
		emsLL.setOnClickListener(this);
		sunFengCheck=(ImageView) findViewById(R.id.mydelivergoods_sunfengCheck);
		emsCheck=(ImageView) findViewById(R.id.mydelivergoods_emsCheck);
		expressNumberEd=(EditText) findViewById(R.id.mydelivergoods_ExpressNumber);
		expressNumberEd.addTextChangedListener(mTextChangedListener);
		goods_address=(TextView) findViewById(R.id.mydelivergoods_address);
		goods_address.addTextChangedListener(mTextChangedListener);
		addressRL=(RelativeLayout) findViewById(R.id.mydelivergoods_addressRL);
		addressRL.setOnClickListener(this);
		//获取默认快递公司(默认顺丰) 和快递公司ID（默认ID：29）
		getExpressID("顺丰快递");
		getDefaultAddress();
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.title_right:
			//确认按钮
			deliverGoods();
			break;
		case R.id.mydelivergoods_sunfeng:
			//顺丰
			getExpressID("顺丰快递");
			sunFengCheck.setImageResource(R.drawable.paiz_information_select_sel2);
			emsCheck.setImageResource(R.drawable.paiz_information_select_nor);
			break;
		case R.id.mydelivergoods_ems:
			//EMS
			getExpressID("EMS");
			sunFengCheck.setImageResource(R.drawable.paiz_information_select_nor);
			emsCheck.setImageResource(R.drawable.paiz_information_select_sel2);
			break;
		case R.id.mydelivergoods_addressRL:
			//地址选择
			intent =new Intent(mContext,AddressManagement_Activity.class);
			startActivityForResult(intent, 1);
			break;
		default:
			break;
		}
	}

	/**
	 * 获取快递ID号
	 */
	private void getExpressID(String expressName){
		Boolean isGetExpressID=false;//是否获取到了快递信息
		ClasslistParse bean = (ClasslistParse) DataKeeper.readSerializable(mContext, ClasslistParse.class);
		if (bean != null) {
			list_express = bean.getExpress_list();
		} else {
			list_express = new ArrayList<ClasslistParse.Classlist>();
		}
		for (int i = 0; i < list_express.size(); i++) {
			if(expressName.equals(list_express.get(i).getName())){
				isGetExpressID=true;
				express=expressName;
				express_id=list_express.get(i).getId();
			}
		}
		//如果没获取到快递信息就手动填写
		if(isGetExpressID==false){
			if("顺丰快递".equals(expressName)){
				express=expressName;
				express_id="29";
			}else if("EMS".equals(expressName)){
				express=expressName;
				express_id="8";
			}
		}
	}
	/**
	 * 对EditText/TextView监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			//对按钮的判断是否可用
			if(!StringUtils.isEmpty(expressNumberEd.getText().toString()) && !StringUtils.isEmpty(goods_address.getText().toString())){
				titleRight_tv.setEnabled(true);
				titleRight_tv.setTextColor(Color.parseColor("#897C5B"));
			}else{
				titleRight_tv.setEnabled(false);
				titleRight_tv.setTextColor(Color.parseColor("#D0D0D0"));
			}
		}  
	};  

	/**
	 * 获取默认地址
	 */
	private void getDefaultAddress(){
		VolleyBasic.getInstance(this).post(Cache.defaultAddressInfo,
				VolleyMap.getInstance().defaultAddressInfo(),
				DefaultAddressParser.class,new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				DefaultAddressParser bean=(DefaultAddressParser) vd.getData();
				address_id=bean.getAddress_id();
				goods_address.setText(bean.getAreaname()+" "+bean.getCityname()+" "+ bean.getAddress());
			}

			@Override
			public void onError(VolleyError volleyError) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 发货请求
	 * 用户口令	token
		订单ID	order_id
		快递公司ID	id
		快递单号	shipping_code
		地址ID	address_id
		快递方式	express
	 */
	private void deliverGoods(){
		VolleyBasic.getInstance(this).post(Cache.express,
				VolleyMap.getInstance().express(order_id, express_id, expressNumberEd.getText().toString(), address_id, "快递"),
				OneStateParser.class,new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				OneStateParser bean=(OneStateParser) vd.getData();
				if("1".equals(bean.getState())){
					//发货成功
					Intent intent = new Intent("com.TransactionManagement_Activity.receiver");  
					intent.putExtra("Intent_type", "我要发货");
					mContext.sendBroadcast(intent);
					Intent intent2 = new Intent("com.OrderInfo_Activity.receiver");  
					intent2.putExtra("Intent_type", "我要发货");
					mContext.sendBroadcast(intent2);
					if(getIntent().getBooleanExtra("isPush", false)==true){
						Intent intent3=new Intent(mContext,TransactionManagement_Activity.class);
						intent3.putExtra("IsShowOtherActivity", true);
						intent3.putExtra("whichActivity", 3);
						startActivity(intent3);
						ArtWorkApp.getInstance().exit(ArtWorkApp.activityList.size()-1);
						ArtWorkApp.getInstance().exit(ArtWorkApp.activityList.size()-2);
						ArtWorkApp.getInstance().exit(ArtWorkApp.activityList.size()-3);
					}
					finish();
				}else{
					showToast("发货失败,请重新尝试发货");
				}
			}

			@Override
			public void onError(VolleyError volleyError) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 之前页面关闭数据接收
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		// TODO Auto-generated method stub  
		super.onActivityResult(requestCode, resultCode, data);  
		if (requestCode == 1 && resultCode == RESULT_OK) { 
			//获取返回的尺寸
			if(data!=null){
				if(!StringUtils.isEmpty(data.getStringExtra("address_id"))){
					//获取地址ID
					address_id=data.getStringExtra("address_id");
					goods_address.setText(data.getStringExtra("address_info"));
				}
			}
		}
	}

	// 广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getBooleanExtra("addAndUpdataAddress", false)==true){
				address_id=intent.getStringExtra("address_id");
				goods_address.setText(intent.getStringExtra("address_info"));
			}
			if(intent.getBooleanExtra("addressNull", false)){
				goods_address.setText("");
				address_id="";
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}
}
